﻿
function MsgAlert(result,timeOut) {
    var msgWin = Ext.Msg.alert('信息', result);

    setTimeout(function () {
        msgWin.hide();
    }, timeOut);
}


function serializeJson(id) {
    var myForm = Ext.getCmp(id).getForm();

    var items = myForm.getFields().items;
    var obj = new Object();

    Ext.each(items, function (item) {

        if (item.name == undefined) {
            return true;
        }
        var v = item.getValue();

        if (item.xtype == "netmulticombo") {

            var temp = "";
            var i = 0;
            Ext.each(v, function (item) {
                if (i > 0) {
                    temp += ",";
                }
                temp += item;
                i++;
            });
            if (item.name != undefined && item.name != "") {
                obj[item.name] = temp;
            }
        }
        else {
            if (typeof (v) == "string") {
                obj[item.name] = Ext.String.trim(v);
            }
            else {
                obj[item.name] = v;
            }
        }

    });

    return obj;
}

function serializeJsonContainer(id) {
    var myForm = Ext.getCmp(id);

    var items = myForm.items;
    var obj = new Object();

    Ext.each(items.items, function (item) {

        if (item.name == undefined) {
            return true;
        }

        if (item.xtype == 'container') {
            setObject(item.id, obj);
        }

        var v = item.getValue();


        if (v == undefined) {
            v = null;
        }

        if (item.xtype == "netmulticombo") {

            var temp = "";
            var i = 0;
            Ext.each(v, function (item) {
                if (i > 0) {
                    temp += ",";
                }
                temp += item;
                i++;
            });
            obj[item.name] = temp;
        }
        else {
            if (typeof (v) == "string") {
                obj[item.name] = Ext.String.trim(v);
            }
            else {
                obj[item.name] = v;
            }
        }

    });

    return obj;
}

function setObject(id, obj) {
    var myForm = Ext.getCmp(id);

    var items = myForm.items;

    Ext.each(items.items, function (item) {

        if (item.name == undefined) {
            return true;
        }

        if (item.xtype == 'container') {
            setObject(item.id, obj);
        }

        var v = item.getValue();
        if (v == undefined) {
            v = null;
        }

        if (item.xtype == "netmulticombo") {

            var temp = "";
            var i = 0;
            Ext.each(v, function (item) {
                if (i > 0) {
                    temp += ",";
                }
                temp += item;
                i++;
            });
            obj[item.name] = temp;
        }
        else {
            if (typeof (v) == "string") {
                obj[item.name] = Ext.String.trim(v);
            }
            else {
                obj[item.name] = v;
            }
        }

    });

    return obj;
}


function checkIsValid(id) {
    var myForm = Ext.getCmp(id);

    var items = myForm.items;
    var result = true;

    Ext.each(items.items, function (item) {

        if (item.isValid != undefined && !item.isValid()) {
            result = false;
            return;
        }
    });

    return result;

    return obj;
}



function FillDataByJson(formid, obj) {
    var myForm = Ext.getCmp(formid).getForm();

    var items = myForm.getFields().items;
    Ext.each(items, function (item) {
        if (item.xtype == "datefield") {
            var datevalue = obj[item.name];
            if (datevalue) {


                var vDate = new Date(datevalue);
                if (isNaN(vDate)) {
                    var vDate = new Date(datevalue.replace(/-/g, "/"));
                }
                //var mSecondArry = datevalue.split(' ');
                //var   mSecond = mSecondArry[mSecondArry.length - 1];
                //vDate = Ext.Date.add(vDate, Ext.Date.MILLI, mSecond);

                item.setValue(vDate);
            }
        }
        else {

            item.setValue(obj[item.name]);

        }

    });
}

function FillDataByJsonWithTagName(formid, obj, tagName) {
    var myForm = Ext.getCmp(formid).getForm();
    var items = myForm.getFields().items;
    Ext.each(items, function (item) {
        if (item.tag == tagName) {
            if (item.xtype == "datefield") {
                var datevalue = obj[item.name];
                if (datevalue) {

                    var vDate = new Date(datevalue.replace(/-/g, "/"));
                    item.setValue(vDate);
                }
            }
            else {
                item.setValue(obj[item.name]);
            }
        }

    });
}



function isMatchRecord(arrayItems, key, value) {
    var result = false;
    Ext.each(arrayItems, function (item) {
        if (value == item.data[key]) {
            result = true;
            return false;
        }
    });

    return result;
}

function isMatchArray(arrayItems, value) {
    var result = false;
    Ext.each(arrayItems, function (item) {
        if (value == item) {
            result = true;
            return false;
        }
    });

    return result;
}

//创建UrlPanel
function CreateUrlPanel(url, paramsObj, callbackFuc) {
    var panel = new Ext.Panel({
        title: '',
        renderTo: document.body,
        autoLoad: {
            url: url,
            scripts: true,
            discardUrl: false,
            nocache: false,
            renderer: "frame",
            loadMask: {
                showMask: true,
                msg: "页面加载中..."
            },
            callback: callbackFuc,
            params: paramsObj
        }
    });

    return panel;
}

function setCheck(node, checked, eOpts) {

    setChild(node, checked);
    setParent(node, checked);
}

function setChild(node, checked) {
    var childNodes = node.childNodes;
    for (var i = 0; i < childNodes.length; i++) {
        childNodes[i].set("checked", checked);
        setChild(childNodes[i], checked);
    }
}

function setParent(node, checked) {
    if (checked == true) {
        var pNode = node.parentNode;
        if (pNode != null) {
            pNode.set("checked", true);
            setParent(pNode, checked);
        }
    }
}

function UpOne(grid, store) {

    var selectRows = grid.getSelectionModel().getSelection();
    if (selectRows.length == 0) {
        Ext.Msg.alert("请选择行");
        return;
    }

    if (grid.editingPlugin != undefined && grid.editingPlugin.editing == true) {
        return;
    }

    var index = store.indexOf(selectRows[0]); //获取当前记录所在索引
    if (index > 0) {
        var itemCurent = store.data.items[index];
        var itemPre = store.data.items[index - 1];

        for (var s in itemCurent.data) {
            var temp = itemCurent.data[s];
            itemCurent.data[s] = itemPre.data[s];
            itemPre.data[s] = temp;
        }
        grid.getView().refresh();
        grid.getSelectionModel().select(index - 1); //新插入一行被选中
    }
}

function DownOne(grid, store) {

    var selectRows = grid.getSelectionModel().getSelection();
    if (selectRows.length == 0) {
        Ext.Msg.alert("请选择行");
        return;
    }

    if (grid.editingPlugin != undefined && grid.editingPlugin.editing == true) {
        return;
    }

    var index = store.indexOf(selectRows[0]); //获取当前记录所在索引
    if (index < store.data.items.length - 1) {
        var itemCurent = store.data.items[index];
        var itemNext = store.data.items[index + 1];

        for (var s in itemCurent.data) {
            var temp = itemCurent.data[s];
            itemCurent.data[s] = itemNext.data[s];
            itemNext.data[s] = temp;
        }
        grid.getView().refresh();

        grid.getSelectionModel().select(index + 1); //新插入一行被选中

    }
}

window.onload = function () {

    document.getElementsByTagName("body")[0].onkeydown = function () {

        //获取事件对象  
        var elem = event.relatedTarget || event.srcElement || event.target || event.currentTarget;

        if (event.keyCode == 8) {//判断按键为backSpace键  

            //获取按键按下时光标做指向的element  
            var elem = event.srcElement || event.currentTarget;

            //判断是否需要阻止按下键盘的事件默认传递  
            var name = elem.nodeName;

            if (name != 'INPUT' && name != 'TEXTAREA') {
                return _stopIt(event);
            }
            var type_e = elem.type.toUpperCase();
            if (name == 'INPUT' && (type_e != 'TEXT' && type_e != 'TEXTAREA' && type_e != 'PASSWORD' && type_e != 'FILE')) {
                return _stopIt(event);
            }
            if (name == 'INPUT' && (elem.readOnly == true || elem.disabled == true)) {
                return _stopIt(event);
            }
        }
    }
}

function _stopIt(e) {
    if (e.returnValue) {
        e.returnValue = false;
    }
    if (e.preventDefault) {
        e.preventDefault();
    }

    return false;
}


function setPercent(id, selectRow) {
    var myForm = Ext.getCmp(id).getForm();
    var items = myForm.getFields().items;

    Ext.each(items, function (item) {
        if (item.xtype == "numberfield") {
            var name = item.name;
            var v = selectRow.data[name];
            if (v != undefined && v != null) {
                var result = (parseFloat(v) * 100).toFixed(4);
                item.setValue(result);
            }
        }
    });
}

function setPercentObj(obj, key) {
    if (obj[key] != undefined && obj[key] != null) {
        var v = obj[key];
        var result = (parseFloat(v) / 100).toFixed(6);
        obj[key] = result;
    }
}

Ext.override(Ext.form.NumberField, {

    /**
    * @cfg {Boolean} useThousandSeparator
    */
    useThousandSeparator: true,

    /**
     * @inheritdoc
     */
    toRawNumber: function (value) {
        return String(value).replace(this.decimalSeparator, '.').replace(new RegExp(Ext.util.Format.thousandSeparator, "g"), '');
    },

    /**
     * @inheritdoc
     */
    getErrors: function (value) {
        if (!this.useThousandSeparator)
            return this.callParent(arguments);
        var me = this,
            errors = Ext.form.field.Text.prototype.getErrors.apply(me, arguments),
            format = Ext.String.format,
            num;

        value = Ext.isDefined(value) ? value : this.processRawValue(this.getRawValue());

        if (value.length < 1) { // if it's blank and textfield didn't flag it then it's valid
            return errors;
        }

        value = me.toRawNumber(value);

        if (isNaN(value.replace(Ext.util.Format.thousandSeparator, ''))) {
            errors.push(format(me.nanText, value));
        }

        num = me.parseValue(value);

        if (me.minValue === 0 && num < 0) {
            errors.push(this.negativeText);
        }
        else if (num < me.minValue) {
            errors.push(format(me.minText, me.minValue));
        }

        if (num > me.maxValue) {
            errors.push(format(me.maxText, me.maxValue));
        }

        return errors;
    },

    /**
     * @inheritdoc
     */
    valueToRaw: function (value) {
        if (!this.useThousandSeparator)
            return this.callParent(arguments);
        var me = this;
        var decimalNum = this.decimalPrecision;
        var format = "0,000,000";
        if (this.allowDecimals == true) {
            if (decimalNum > 0) {
                format += ".";
            }
            for (var i = 0; i < decimalNum; i++) {
                format += "0";
            }
        }


        value = me.parseValue(Ext.util.Format.number(value, format));
        value = me.fixPrecision(value);
        value = Ext.isNumber(value) ? value : parseFloat(me.toRawNumber(value));
        value = isNaN(value) ? '' : String(Ext.util.Format.number(value, format)).replace('.', me.decimalSeparator);
        return value;
    },

    /**
     * @inheritdoc
     */
    getSubmitValue: function () {
        if (!this.useThousandSeparator)
            return this.callParent(arguments);
        var me = this,
            value = me.callParent();

        if (!me.submitLocaleSeparator) {
            value = me.toRawNumber(value);
        }
        return value;
    },

    /**
     * @inheritdoc
     */
    setMinValue: function (value) {
        if (!this.useThousandSeparator)
            return this.callParent(arguments);
        var me = this,
            allowed;

        me.minValue = Ext.Number.from(value, Number.NEGATIVE_INFINITY);
        me.toggleSpinners();

        // Build regexes for masking and stripping based on the configured options
        if (me.disableKeyFilter !== true) {
            allowed = me.baseChars + '';

            if (me.allowExponential) {
                allowed += me.decimalSeparator + 'e+-';
            }
            else {
                allowed += Ext.util.Format.thousandSeparator;
                if (me.allowDecimals) {
                    allowed += me.decimalSeparator;
                }
                if (me.minValue < 0) {
                    allowed += '-';
                }
            }

            allowed = Ext.String.escapeRegex(allowed);
            me.maskRe = new RegExp('[' + allowed + ']');
            if (me.autoStripChars) {
                me.stripCharsRe = new RegExp('[^' + allowed + ']', 'gi');
            }
        }
    },
    setCaretPosition: function (pos) {
        var el = this.inputEl.dom;
        if (typeof (el.selectionStart) === "number") {
            el.focus();
            el.setSelectionRange(pos, pos);
        } else if (el.createTextRange) {
            var range = el.createTextRange();
            range.move("character", pos);
            range.select();
        } else {
            throw 'setCaretPosition() not supported';
        }
    },

    getCaretPosition: function () {
        var el = this.inputEl.dom;
        if (typeof (el.selectionStart) === "number") {
            return el.selectionStart;
        } else if (document.selection && el.createTextRange) {
            var range = document.selection.createRange();
            range.collapse(true);
            range.moveStart("character", -el.value.length);
            return range.text.length;
        } else {
            throw 'getCaretPosition() not supported';
        }
    },
    /**
     * @private
     */
    parseValue: function (value) {
        if (!this.useThousandSeparator)
            return this.callParent(arguments);
        value = parseFloat(this.toRawNumber(value));
        return isNaN(value) ? null : value;
    },
    constructor: function () {

        this.callParent(arguments);
        if (this.useThousandSeparator == true) {
            this.on('focus', function (v1) {
                var decimalNum = this.decimalPrecision;
                var formatNum = "0";
                if (this.allowDecimals == true) {
                    if (decimalNum > 0) {
                        formatNum += ".";
                    }
                    for (var i = 0; i < decimalNum; i++) {
                        formatNum += "0";
                    }
                }
                var sourceStr = v1.getRawValue();
                var v = v1.getRawValue();
                v = typeof v == 'number' ? v : String(v).replace(this.decimalSeparator,
    ".").replace(/,/g, "");
                var Rv = isNaN(v) ? v : Ext.util.Format.number(
    this.fixPrecision(String(v)), formatNum);

                var indexNum = this.getCaretPosition();

                for (var i = 0; i <= indexNum; i++) {
                    if (sourceStr.charAt(i) == ',') {
                        indexNum--;
                    }
                }
                v1.setValue(Rv);
                v1.setRawValue(Rv);
                this.setCaretPosition(indexNum);
            });
        }

    }
});